import { extend, isObject } from "../shared/index";
import { track, trigger } from "./effect";
import { ReactiveFlags, reactive, readonly } from "./reactive";

const get = createGetter()
const set = createSetter()
const readonlyGet = createGetter(true)
const shallowReadonlyGet = createGetter(true,true)

function createGetter(isReadonly = false,shallow = false) {
    return function get(target,key) {
        const res = Reflect.get(target,key);
        if(key === ReactiveFlags.IS_REACTIVE) {
            return !isReadonly
        } else if(key === ReactiveFlags.IS_READONLY) {
            return isReadonly
        }
        if(shallow) {
            return res
        }
        if(!isReadonly) { 
            // TODO 依赖收集
            track(target,key)
        }
        // 看res 是不是 Object
        if(isObject(res)) {
            return isReadonly ? readonly(res) : reactive(res)
        } 
        return res
    }
}

function createSetter() {
    return function set(target,key,value) {
        const res = Reflect.set(target,key,value);
        // TODO 触发依赖
        trigger(target,key)
        return res
    }
}

export const mutableHandlers = {
    get,
    set
}

export const readonlyHandlers = {
    get:readonlyGet,
    set(target,key,value) {
        console.warn(`key: ${key} set 失败 因为 target 是 readonly`,target);
        return true
    },
}

// *采用extend继承的方式（第一个参数是空对象，第二个参数是要继承的对象，第三个对象是要改写的内容）
export const shallowReadonlyHandlers = extend({},readonlyHandlers,{
    get:shallowReadonlyGet
})